package account

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"insighttracking/common/utils"
	"insighttracking/query/dao"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyPasswordApiLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewModifyPasswordApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ModifyPasswordApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyPasswordApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ModifyPasswordApiLogic) ModifyPasswordApi(req *types.ModifyPasswordReq) (resp string, err error) {
	if req.Password != req.ConfirmPassword {
		return "", errors.New("两次密码不一致")
	}
	if req.AccountID == 1 {
		l.Logger.Error("管理员不能被修改")
		return "", errors.New("删除修改")
	}
	salt := utils.GeneratorString(utils.GeneratorRandom(5, 10))
	newPassword := utils.Md5(req.Password, salt)
	if _, err = dao.AccountEntity.WithContext(l.ctx).Where(dao.AccountEntity.AccountID.Eq(req.AccountID)).UpdateSimple(
		dao.AccountEntity.Password.Value(newPassword),
		dao.AccountEntity.Salt.Value(salt),
	); err != nil {
		l.Logger.Error("修改密码失败" + err.Error())
		return "", errors.New("修改失败")
	}
	return
}
